<template>
    <el-form label-width="100px">
        <el-form-item label="SPU名称" prop="">
            <el-input placeholder="请你输入SPU名称" v-model="SpuParams.spuName"></el-input>
        </el-form-item>
        <el-form-item label="SPU品牌" prop="">
            <el-select allow-create style="width: 30%;" v-model="SpuParams.tmId">
                <el-option :label="item.tmName" v-for="(item, index) in AllTrademark" :key="item.id"
                    :value="item.id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="SPU描述" prop="">
            <el-input placeholder="请你输入SPU描述" type="textarea" v-model="SpuParams.description"></el-input>
        </el-form-item>
        <el-form-item label="SPU图片" prop="">
            <el-upload action="/api/admin/product/fileUpload" list-type="picture-card" v-model:file-list="imgList"
                :on-preview="handle" :on-remove="handleRemove" :before-upload="handleUpload">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
                <img w-full alt="Preview Image" :src="dialogImageUrl" style="width: 100%;height: 100%;" />
            </el-dialog>
        </el-form-item>
        <el-form-item label="SPU销售属性" prop="">
            <el-select allow-create style="width: 30%;"
                :placeholder="unSelectSaleAttr.length ? `还有${unSelectSaleAttr.length}个未选择` : '无'"
                v-model="saleAttrAndValueName">
                <el-option :label="item.name" v-for="(item, index) in unSelectSaleAttr" :key="item.id"
                    :value="`${item.id}:${item.name}`"></el-option>
            </el-select>
            <el-button type="primary" @click="addSaleAttr" icon="Plus" style="margin-left: 10px;"
                :disabled="saleAttrAndValueName ? false : true">添加属性</el-button>
            <el-table border style="margin: 10px 0;" :data="saleAttrList">
                <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
                <el-table-column label="销售属性名字" width="120px" prop="saleAttrName"></el-table-column>
                <el-table-column label="销售属性值">
                    <template #="{ row, $index }">
                        <el-tag style="margin:0px 5px" @close="row.spuSaleAttrValueList.splice(index, 1)"
                            v-for="(item, index) in row.spuSaleAttrValueList" :key="row.id" class="mx-1" closable>
                            {{ item.saleAttrValueName }}
                        </el-tag>
                        <el-input @blur="toLook(row)" v-model="row.saleAttrValue" v-if="row.flag == true"
                            placeholder="请你输入属性值" size="small" style="width: 100px;"></el-input>
                        <el-button type="primary" v-else size="small" @click="toEdit(row)" icon="Plus"> </el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120px">
                    <template #="{ row, $index }">
                        <el-button type="primary" size="small" @click="saleAttrList.splice($index, 1)"
                            icon="Delete"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item label="" prop="">
            <el-button type="primary" @click="save" :disabled="saleAttrList.length > 0 ? false : true">保存</el-button>
            <el-button type="primary" @click="cancel">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup lang='ts'>
import type { SupData } from '@/api/product/spu/type'
import { reqBaseSpu, reqAllTradeMark, reqAllSaleAttr, reqAddSpuOrUpdateSpu } from '@/api/product/spu';
import type { Trademark, AllTradeMark, BaseSpuResponseData, SpuImageList, SpuSaleAttrList, AllSaleAttrResponseData, AllSaleAttr } from '@/api/product/spu/type'
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
let $emit = defineEmits(['changeScene'])
//存储已有的spu的数据
let AllTrademark = ref<Trademark[]>([])
let imgList = ref<any[]>([])
//已有的销售属性
let saleAttrList = ref<SpuSaleAttrList[]>([])
//全部销售属性
let allSaleAttr = ref<AllSaleAttr[]>([]);
//收集还未选择的销售属性的id与属性值的名字
let saleAttrAndValueName = ref<string>('')
let SpuParams = ref<SupData>({
    category3Id: "",//收集三级分类的ID
    spuName: "",//SPU的名字
    description: "",//SPU的描述
    tmId: '',//品牌的ID
    spuImageList: [],
    spuSaleAttrList: [],
    spuPosterList: []
})
const cancel = () => {
    $emit('changeScene', {
        flag: 0, params: 'update'
    })
}
const initHasSpuData = async (spu: SupData) => {
    SpuParams.value = spu
    let result: AllTradeMark = await reqAllTradeMark()
    let result1: BaseSpuResponseData = await reqBaseSpu((spu.id as number))
    let result2: AllSaleAttrResponseData = await reqAllSaleAttr();
    AllTrademark.value = result.data
    imgList.value = result1.data.spuImageList.map(item => {
        return {
            name: item.imgName,
            url: item.imgUrl
        }
    })
    saleAttrList.value = result1.data.spuSaleAttrList
    allSaleAttr.value = result2.data
}
let dialogVisible = ref<boolean>(false)
let dialogImageUrl = ref<string>('')
// /照片墙点击预览
const handle = (file: any) => {
    dialogImageUrl.value = file.url
    dialogVisible.value = true
}
//照片墙删除
const handleRemove = () => {

}
//照片墙上传成功前约束文件的大小与类型
const handleUpload = (file: any) => {
    if (file.type == 'image/png' || file.type == 'image/jpeg' || file.type == 'image/gif') {
        if (file.size / 1024 / 1024 < 3) {
            return true
        } else {
            ElMessage({
                type: 'error',
                message: '上传文件需要小于3M'
            })
            return false
        }
    } else {
        ElMessage({
            type: 'error',
            message: '上传文件限制为PNG|GIF|JEPG'
        })
        return false
    }
}
//计算出SPU还未拥有的属性
let unSelectSaleAttr = computed(() => {
    let unSelectArr = allSaleAttr.value.filter(item => {
        return saleAttrList.value.every(item1 => {
            return item.name != item1.saleAttrName
        })
    })
    return unSelectArr
})
//添加销售属性的方法
const addSaleAttr = () => {
    const [baseSaleAttrId, saleAttrName] = saleAttrAndValueName.value.split(":")
    //准备一个新的销售属性对象：将来带给服务器
    let newSaleAttr: any = {
        baseSaleAttrId,
        saleAttrName,
    }
    saleAttrList.value.push(newSaleAttr)
}
//属性值按钮的点击事件
const toEdit = (row: any) => {
    row.flag = true
    row.saleAttrValue = ''
}
//表单元素失去焦点的事件
const toLook = (row: any) => {
    //整理收集的属性的id与属性值的名字
    const { baseSaleAttrId, saleAttrValue } = row
    //整理成服务器需要的属性值的形式
    let newSaleAttrValue = {
        baseSaleAttrId,
        saleAttrValueName: saleAttrValue
    }
    //是否输入的值为空
    if (saleAttrValue.trim() == '') {
        ElMessage({
            type: 'error',
            message: '属性值不能为空'
        })
        return;
    }
    //判断属性值是否存在
    let repeat = row.spuSaleAttrValueList.find((item: any) => {
        return item.saleAttrValueName == saleAttrValue
    })
    if (repeat) {
        ElMessage({
            type: 'error',
            message: '属性值重复'
        })
        return;
    }
    //追加新的属性值对象
    row.spuSaleAttrValueList.push(newSaleAttrValue)
    row.flag = false
}
//保存按钮
const save = async () => {
    // 照片墙·的数据
    (SpuParams.value.spuImageList as any) = imgList.value.map(item => {
        return {
            imgName: item.name,
            imgUrl: (item.response && item.response.data) || item.url
        }
    })
    //整理销售属性的数据
    SpuParams.value.spuSaleAttrList = saleAttrList.value
    //发请求更新或是添加
    let result = await reqAddSpuOrUpdateSpu(SpuParams.value)
    if (result.code == 200) {
        ElMessage({
            type: "success",
            message: SpuParams.value.id ? '修改成功' : "添加成功"
        })
        //通知父组件切换场景为0
        $emit('changeScene', { flag: 0, params: SpuParams.value.id ? 'update' : 'add' })
    } else {
        ElMessage({
            type: "error",
            message: SpuParams.value.id ? '修改失败' : "添加失败"
        })
    }
}
//添加一个新的SPU
const initAddSpu = async (c3Id: number | string) => {
    //清空数据
    Object.assign(SpuParams.value, {
        category3Id: "",//收集三级分类的ID
        spuName: "",//SPU的名字
        description: "",//SPU的描述
        tmId: '',//品牌的ID
        spuImageList: [],
        spuSaleAttrList: [],
        spuPosterList: []
    })
    //清空照片
    imgList.value = []
    //清空销售属性
    saleAttrList.value = []
    saleAttrAndValueName.value = ''
    SpuParams.value.category3Id = c3Id
    let result: AllTradeMark = await reqAllTradeMark()
    let result2: AllSaleAttrResponseData = await reqAllSaleAttr();
    AllTrademark.value = result.data
    allSaleAttr.value = result2.data
}
defineExpose({ initHasSpuData, initAddSpu })
</script>

<style></style>